package cn.kgc.mcartoon.interator;

import cn.kgc.mcartoon.dto.ResultDto;
import cn.kgc.mcartoon.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 认证拦截器
 */
@Component
public class AuthenticationInterator extends HandlerInterceptorAdapter {


    private JwtUtil jwtUtil = new JwtUtil();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 是否登录
        boolean isLogin = false;

        // 请求头带上令牌 Authorization: Bearer jwtToken
        final String authHeader = request.getHeader("Authorization");

        if(StringUtils.isNotBlank(authHeader) && authHeader.startsWith("Bearer ")) {
            // 截取token，
            final String token = authHeader.substring(7);
            // 解析token
            Claims claims = jwtUtil.parseJWT(token);
            if(claims != null) {
                // 是否登录
                Boolean b = (Boolean) claims.get("isLogin");
                if(b) {
                    // 已经登录，放行请求
                    isLogin = true;
                }
            }
        }

        if(!isLogin) {
            // 未登录，则响应信息
            response.setContentType("application/json;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            response.setStatus(401);
            response.getWriter().write(ResultDto.error("请先登录后访问").toString());
        }
        //
        return isLogin;
    }
}